<?php

namespace lib\tools\elasticsearch;

use \Elasticsearch\ClientBuilder;
use lib\tools\singleton\Single;
use modules\tracing\zipkin\ZipkinTracing;

/**
 * @method static \Elasticsearch\Client getInstance($sign = '')
 */
class CoreEs extends Single implements \constant\db\Common, \constant\api\Code
{

    const REPLACE_MAP = [
        '。' => '|||',
        '.' => '||',
    ];

    const SEARCH_REPLACE_MAP = [
        '|||' => '。',
        '||' => '.',
        "\n" => '<br/>',
    ];

    const FORMAT_TYPE_HTML_TO_ES = 1;
    const FORMAT_TYPE_ES_TO_EDIT = 2;
    const FORMAT_TYPE_ES_TO_SEARCH = 3;

    /**
     * @return \Elasticsearch\Client
     * @throws \Matomo\Ini\IniReadingException
     * @throws \ReflectionException
     */
    public static function instance()
    {
        $tracing = ZipkinTracing::start(ZipkinTracing::SERVERNAME_ES);

        $config = \lib\tools\config\EsConfig::getInstance('es');

        $span = $tracing->span(ZipkinTracing::SPAN_ES_CONNECT, [
            ['读取配置,hosts:', $config->hosts],
            ['读取配置,user:', $config->user],
        ]);

        $client = ClientBuilder::create()
            ->setHosts([$config->hosts])
            ->setBasicAuthentication($config->user, $config->passwd)
            ->build();

        $span->finish();

        return $client;
    }

    public static function html2es($content)
    {
        foreach (self::REPLACE_MAP as $find => $replace) {
            $content = str_replace($find, $replace, $content);
        }
        return $content;
    }

    public static function es2html($content)
    {
        foreach (self::REPLACE_MAP as $find => $replace) {
            $content = str_replace($replace, $find, $content);
        }
        return $content;
    }

    public static function es2search($content)
    {
        foreach (self::SEARCH_REPLACE_MAP as $find => $replace) {
            $content = str_replace($find, $replace, $content);
        }
        return $content;
    }

    public static function format($value, $style = 'info')
    {
        $valueArr = is_array($value) ? $value : [$value];
        $valueArr = array_map(function ($item) use ($style) {
            return strlen($item) ? "<span class='badge badge-{$style} '>$item</span>" : '';
        }, $valueArr);
        return implode(" ", $valueArr);
    }
}